<template>
  <Card class="card_style" :bordered="false" :dis-hover="true">
    <Row class="bench_search">
      <Col span="4">
        <span>标题：</span>
        <Input style="width: 70%;" v-model="searchInfo.title" />
      </Col>
      <Col span="4">
        <span>类别：</span>
        <Select v-model="searchInfo.dic" style="width: 75%;" filterable>
          <Option value="">全部</Option>
          <Option v-for="(item,i) in dicList" :key="i" :value="item.id">{{item.title}}</Option>
        </Select>
      </Col>
      <Button type="info" style="margin-right:10px" @click="searchData(false)"><Icon type="ios-search" /> 搜索</Button>
      <Button type="success" @click="create" style="margin-left:10px"><Icon type="md-add" /> 创建</Button>
    </Row>
    <Modal v-model="modalShowType" title="新增类别" :mask-closable="false">
        <Form :model="formItemTitle" :label-width="80" ref="ruleValidateType" :rules="ruleValidateType">
            <FormItem label="类别名称:" prop="title">
                <Input v-model="formItemTitle.title" :disabled="disable" placeholder="类别名称"></Input>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="info" @click="addOkType('ruleValidateType')">添加</Button>
            <Button type="default" @click="closeModelType">关闭</Button>
        </div>
    </Modal>
    <Modal v-model="modalShow" :title="title" :mask-closable="false" width="50%">
      <Form :model="formItem" :label-width="80" ref="ruleValidate" :rules="ruleValidate">
        <FormItem label="标题:" prop="title">
          <Input v-model="formItem.title" :disabled="disable" placeholder="标题"></Input>
        </FormItem>
        <FormItem label="时间:" prop="time">
          <DatePicker type="date" :disabled="disable" style="width: 100%" v-model="formItem.time" placeholder="时间"></DatePicker>
        </FormItem>
        <FormItem label="类别:" prop="dic">
          <Select v-model="formItem.dic" :disabled="disable" @on-change="openDic" filterable>
            <Option v-for="(item,i) in dicList" :key="i" :value="item.id">{{item.title}}</Option>
            <Option value="add"><span @click="openDic">自定义添加类别</span></Option>
          </Select>
        </FormItem>
        <FormItem label="内容:">
          <Input v-model="formItem.info" type="textarea" :disabled="disable" placeholder="内容"></Input>
        </FormItem>
        <div>
					<Upload v-if="type !== '3'" multiple type="drag" action="http://120.27.63.37:38081/api/ac/file/fileCommonService/upLoadFiles" :before-upload="beforeUpload" style="margin-left: 80px">
							<!-- <Button icon="ios-cloud-upload-outline">上传附件</Button>
							<span style="margin-left: 100px">请上传小于100M的文件（.jpg/.png/.ico/.pdf/.doc/.docx/.excel）</span> -->
						<div style="padding: 20px 0">
							<Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
							<p>请上传小于100M的附件(.jpg/.png/.pdf/.doc/.excel)</p>
						</div>
					</Upload>
					<br/>
					<div v-if="formItem.files || fileUrlList.length > 0">
						<Row :gutter="20">
							<Col span="6">
								附件点击下载：
							</Col>
							<Col span="16">
								<div v-for="(item, index) in fileUrlList" :key="index" >
									<a :href="item" :title="item" style="color: #457eca; font-size: 14px;">{{item.substring(0, item.indexOf('?')).substring(item.lastIndexOf('/')).substring(1)}}</a>
								</div>
							</Col>
						</Row>
					</div>
        </div>
      </Form>
      <!-- <Checkbox disabled v-model="formItem.status"></Checkbox> -->
      <div slot="footer">
        <Button type="info" v-if="type==='1' && type !== '3'" @click="addOk('ruleValidate')">添加</Button>
        <Button type="info" v-if="type==='2' && type !== '3'" @click="updateOk('ruleValidate')">保存</Button>
        <Button type="default" @click="closeModel">关闭</Button>
      </div>
    </Modal>
    <Table border :columns="columns" :data="datalist">
      <template slot-scope="{ row, index }" slot="status">
        <span style="color: green" v-if="row.status == '已完成'">已完成</span>
        <span style="color: red" v-if="row.status == '未完成'">未完成</span>
        <span style="color: blue" v-if="row.status == '其他'">其他</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <Button type="info" size="small" style="margin-right: 5px" @click="updateModal(row)">编辑</Button>
        <Button type="success" size="small" style="margin-right: 5px" @click="showModal(row)">详情</Button>
        <Button type="error" size="small" style="margin-right: 5px" @click="remove(row)">删除</Button>
      </template>
    </Table>
    <Page :total="totalnum" :current="currentPageNo" :page-size="currentPageSize" @on-change="change" class="page_style"/>
  </Card>
</template>
<script>
import { createUpLoadFiles, getSign } from '@/api/common'
import { date0str, saveThingDic, deleteThing, updateThing, saveThing, findThingList, getDicList } from '@/api/eventlist'
const validateSpace = (rule, value, callback) => {
  // 模拟异步验证效果
  if (!/^[0-9]+([.]\d{1,2})?$/.test(+value)) {
    callback(new Error('请输入数字或小数点后两位'));
  } else {        
    callback();
  }
};
export default {
  data () {
    return {
      mode: true,
      disable: false,
      formItemTitle: {
        title: ''
      },
      formItem: {
        id: '',
        title: '',
        info: '',
        dic: '',
        time: '',
        status: '',
				type: '',
				files: ''
      },
      searchInfo: {
        title: '',
        dic: ''
      },
      modalShow: false,
      type: '',
      title: '',
      options4: '',
      params: {
        pageNo: '',
        pageSize: ''
      },
      dicList: [],
      modalShowType: false,
      currentPageNo: 1,
      currentPageSize: 10,
      rowList: {},
      totalnum: 0,
      columns: [
        { title: '序号', type: 'index', width: 100, align: 'center' },
        { title: '标题名称', key: 'title2', width: 200, align: 'left' },
        { title: '时间', key: 'time2', width: 200, align: 'left' },
        { title: '类别', key: 'dicTitle2', width: 200, align: 'left' },
        { title: '创建单位', key: 'company_name', width: 220, align: 'left' },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          slot: 'action',
          className: 'nopadding',
          minWidth: 100
        }
      ],
      datalist: [],
      ruleValidate: {
        title: [
          { required: true, message: '标题名称不能为空', trigger: 'blur' }
        ],
        time: [
          { required: true, type: 'date', message: '时间不能为空', trigger: 'change' }
        ],
        dic: [
          { required: true, message: '类别不能为空', trigger: 'change' }
        ]
      },
      ruleValidateType: {
        title: [
          { required: true, message: '类别名称不能为空', trigger: 'blur' }
        ]
      },
			level: this.$store.state.user.severUserInfo.company_grade,
			// 上传hadoop相关
			upPicData: {
        filePath: '',
        fileName: ''
      },
			fileUrlList: [],
			timeStep: '',
			index1: 0
    }
  },
  methods: {
    closeModel () {
      this.modalShow = false
    },
    closeModelType () {
      this.modalShowType = false
      this.formItem.dic = ''
    },
    openDic () {
      if(this.formItem.dic === 'add') {
        this.modalShowType = true
        this.formItemTitle = {}
      }
    },
    create () {
      this.modalShow = true
			this.formItem = {}
			this.fileUrlList = []
      this.type = '1'
      this.title = '新增'
			this.disable = false
    },
    showModal (row) {
      this.modalShow = true
      this.type = '3'
      this.title = '详情'
      this.formItem = row
			this.disable = true
			if (row.files) {
        this.fileUrlList = row.files.split(',')
      }
    },
    updateModal (row) {
      this.modalShow = true
      this.type = '2'
      this.title = '修改'
      this.formItem = row
			this.disable = false
			if (row.files) {
        this.fileUrlList = row.files.split(',')
      }
    },
    // 新增
    addOkType (name) {
      this.$refs[name].validate((valid) => {
          console.log('类别：', valid)
        if (valid) {
          let data = {
            title: this.formItemTitle.title, 
          }
          saveThingDic(data).then(res => {
            if (res.data.errcode === 0) {
              this.initDic()
              this.$Notice.success({ title: '新增类别成功', desc: '' })
              this.closeModelType()
            } else {
              this.$Notice.error({ title: '新增类别失败', desc: res.data.errmsg })
            }
          })
        } else {
          this.$Notice.error({ title: '请输入不为空的项!', desc: '请输入不为空的项!' })
        }
      })
    },
    // 查询接口
    init () {
      let data = {
        pageNo: this.currentPageNo,
        pageSize: this.currentPageSize,
        title: this.searchInfo.title,
        dic: this.searchInfo.dic,
        type: '1'
      }
      findThingList(data).then(res => {
        if (res.data.errcode === 0) {
          this.datalist = res.data.data.results
          this.totalnum = res.data.data.totalRecord
          this.datalist.forEach(item => {
            item.title2 = item.title
            item.time2 = item.time
            item.status2 = item.status
            item.dic2 = item.dic
            item.dicTitle2 = item.dicTitle
          })
        } else {
          this.$Notice.error({
            title: '获取列表失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    async initDic () {
      let data = {
        type: '1'
      }
      await getDicList(data).then(res => {
        if (res.data.errcode === 0) {
          this.dicList = res.data.data
          this.dicList.forEach(i => {
            i.id = i.id + ''
          })
        } else {
          this.$Notice.error({
            title: '获取关系列表失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 新增
    addOk (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = {
            title: this.formItem.title, 
            time: date0str(this.formItem.time), 
            status: '$',
            space: '$',
            area: '$',
            info: this.formItem.info,
            dic: this.formItem.dic, 
            files: this.formItem.files,
            type: '1' // 其他
          }
          saveThing(data).then(res => {
            if (res.data.errcode === 0) {
              this.init()
              this.$Notice.success({ title: '新增成功', desc: '' })
              this.closeModel()
            } else {
              this.$Notice.error({ title: '新增失败', desc: res.data.errmsg })
            }
          })
        } else {
          this.$Notice.error({ title: '请输入不为空的项!', desc: '请输入不为空的项!' })
        }
      })
    },
    // 编辑
    updateOk (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = {
            id: this.formItem.id,
            title: this.formItem.title, 
            time: date0str(this.formItem.time), 
            status: '$',
            space: '$',
            area: '$',
            info: this.formItem.info,
            dic: this.formItem.dic, 
            files: this.formItem.files,
            type: '1' // 其他
          }
          updateThing(data).then(res => {
            if (res.data.errcode === 0) {
              this.init()
              this.formItem = {}
              this.closeModel()
              this.$Notice.success({ title: '编辑成功', desc: '' })
            } else {
              this.$Notice.error({ title: '编辑失败', desc: res.data.errmsg })
            }
          })
        } else {
          this.$Notice.error({ title: '请输入不为空的项!', desc: '请输入不为空的项!' })
        }
      })
    },
    // 删除
    remove (item) {
      var param = {
        id: item.id
      }
      if (confirm('确定删除该条数据吗')) {
        deleteThing(param).then(res => {
          if (res.data.errcode === 0) {
            this.$Notice.success({ title: '删除成功', desc: '' })
            this.init()
          }else {
            this.$Notice.error({ title: '删除失败', desc: res.errmsg })
          }
        })
      }
    },
    searchData (index) {
      this.currentPageNo = 1
      this.init()
    },
    change (pageNo) {
      this.currentPageNo = pageNo
      this.init()
		},
		// 上传相关
		beforeUpload (file) {
      console.log('上传相关操作： ', file)
      var time = new Date().getTime()
      this.timeStep = time.toString()
      this.upPicData.fileName = this.formItem.title + this.timeStep + file.name
      this.upPicData.filePath = this.timeStep
      let that = this
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        let index = reader.result.indexOf('base64,') + 7
        that.upPicData.file = reader.result.substring(index)
        that.upPic(that.upPicData, file)
      }
      return false
    },
    // 上传图片
    upPic (obj, file) {
      var time = new Date().getTime()
      this.timeStep = time.toString()
      let param = {
        filePath: obj.filePath,
        fileName: obj.fileName,
        timestamp: this.timeStep
      }
      if (param.fileName.length > 20) {
        param.fileName = param.fileName.substring(0, 20) + file.name
      }
      getSign(param).then(res => {
        if (res.data.errcode === 0) {
          createUpLoadFiles(res.data.data.docking_url, { sign: res.data.data.sign, timestamp: this.timeStep, filePath: param.filePath, fileName: param.fileName, file: obj.file }).then(res => {
            if (res.data.errcode === 0) {
              let Url = res.data.data
              if (this.formItem.files === undefined || this.formItem.files.length === 0) {
                this.formItem.files = Url
              } else {
                this.formItem.files = this.formItem.files + ',' + Url
              }
              this.fileUrlList.push(Url)
              this.index1 = this.fileUrlList.length - 1
            } else {
              this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
            }
          })
        } else {
          this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
        }
      })
    }
  },
  mounted () {
    this.initDic()
    this.init()
  }
}
</script>

<style lang="less">
  .card_style {
    height: 100%;
    width: 100%;
    overflow: hidden;
    .ivu-card-body {
      padding: 0px;
    }
  }
  .page_style {
    margin-top: 10px;
    text-align: right;
  }
  .bench_search {
    margin-bottom: 10px;
  }
  .nopadding .ivu-table-cell {
    padding: 0px 0px;
  }
  .item1{
    height: 42px;
    line-height: 40px;
  }
</style>
